const bcryptjs = require('bcryptjs')

const { getUserInfo } = require('../service/user.service');
const { userFormateError, userAlreadyExited, userRegisterError, userDoesNotExist, userLoginError,
    invalidPassword } = require("../constant/err.type");
const { has } = require('koa/lib/response');
const userValidator = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    // if (!user_name || !password) {
    //     console.error('用户名或密码为空', ctx.request.body)
    //     ctx.app.emit('error', userFormateError, ctx)
    //     return
    // }
    try {
        if (!user_name || !password) {
            console.error('用户名或密码为空', ctx.request.body)
            ctx.app.emit('error', userFormateError, ctx)
            return
        }
    } catch (error) {
        console.error('用户名或密码为空');
        ctx.app.emit('error', userRegisterError, ctx);
        return
    }
    await next()
}

const verifyUser = async (ctx, next) => {
    const { user_name } = ctx.request.body
    //合理性
    // if (await getUserInfo({ user_name })) {
    //     ctx.app.emit('error', userAlreadyExited, ctx)
    //     return
    // }
    try {
        const res = await getUserInfo({ user_name });
        if (res) {
            console.error('用户名已存在', { user_name });
            ctx.app.emit('error', userAlreadyExited, ctx)
            return
        }
    } catch (err) {
        console.error('用户名已存在');
        ctx.app.emit('error', userRegisterError, ctx);
        return
    }
    await next()
}

const crpytPassword = async (ctx, next) => {
    const { password } = ctx.request.body;
    const salt = bcryptjs.genSaltSync(10);
    const hash = bcryptjs.hashSync(password, salt);
    ctx.request.body.password = hash
    await next()
}

// 
const verifyLogin = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    const res = await getUserInfo({ user_name });
    try {
        if (!res) {
            console.error('用户名不存在');
            return ctx.app.emit('error', userDoesNotExist, ctx)

        }
    } catch (err) {
        console.error(err);
        return ctx.app.emit('error', userLoginError, ctx)
    }

    // 密码是否匹配
    if (!bcryptjs.compareSync(password, res.password)) {
        return ctx.app.emit('error', invalidPassword, ctx);
    }
    await next()
}

module.exports = {
    userValidator,
    verifyUser,
    crpytPassword,
    verifyLogin,
}